import React, { useState, useEffect, useCallback, useMemo } from 'react'
import {
  Input,
  Select,
  Button,
  Space,
  Row,
  Col,
  Dropdown,
  Tag,
  DatePicker,
  Drawer,
  Form,
  Checkbox,
  Radio,
  Divider,
  Typography,
  Tooltip,
  Badge,
  Card,
  List,
  Empty,
  message,
} from 'antd'
import {
  SearchOutlined,
  FilterOutlined,
  ClearOutlined,
  SaveOutlined,
  HistoryOutlined,
  SettingOutlined,
  SortAscendingOutlined,
  SortDescendingOutlined,
  CalendarOutlined,
  TagOutlined,
  UserOutlined,
  DeleteOutlined,
  StarOutlined,
  StarFilled,
} from '@ant-design/icons'
import type { RangePickerProps } from 'antd/es/date-picker'
import dayjs from 'dayjs'
import { getAllTags } from '@/services/scriptAPI'
import { useLocalStorage } from '@/hooks/useLocalStorage'
import { useDebounce } from '@/hooks/useDebounce'

const { Search } = Input
const { Option } = Select
const { RangePicker } = DatePicker
const { Text } = Typography

interface SearchAndFilterProps {
  onSearch?: (keyword: string) => void
  onTagsChange?: (tags: string[]) => void
  onSortChange?: (sortBy: string, sortOrder: 'asc' | 'desc') => void
  onFilterChange?: (filters: FilterOptions) => void
  defaultKeyword?: string
  defaultTags?: string[]
  defaultSortBy?: string
  defaultSortOrder?: 'asc' | 'desc'
  showAdvancedFilter?: boolean
  showSortOptions?: boolean
  showSaveSearch?: boolean
}

interface FilterOptions {
  dateRange?: [string, string]
  createdBy?: string[]
  hasDescription?: boolean
  hasContent?: boolean
  minVersions?: number
  maxVersions?: number
  lastExecutedRange?: [string, string]
  contentLength?: {
    min?: number
    max?: number
  }
}

interface SavedSearch {
  id: string
  name: string
  keyword: string
  tags: string[]
  filters: FilterOptions
  sortBy: string
  sortOrder: 'asc' | 'desc'
  createdAt: string
  isFavorite: boolean
}

const SearchAndFilter: React.FC<SearchAndFilterProps> = ({
  onSearch,
  onTagsChange,
  onSortChange,
  onFilterChange,
  defaultKeyword = '',
  defaultTags = [],
  defaultSortBy = 'updated_at',
  defaultSortOrder = 'desc',
  showAdvancedFilter = true,
  showSortOptions = true,
  showSaveSearch = true,
}) => {
  // 基础状态
  const [keyword, setKeyword] = useState(defaultKeyword)
  const [selectedTags, setSelectedTags] = useState<string[]>(defaultTags)
  const [sortBy, setSortBy] = useState(defaultSortBy)
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>(defaultSortOrder)
  const [filters, setFilters] = useState<FilterOptions>({})

  // UI状态
  const [filterDrawerVisible, setFilterDrawerVisible] = useState(false)
  const [saveSearchModalVisible, setSaveSearchModalVisible] = useState(false)
  const [searchHistoryVisible, setSearchHistoryVisible] = useState(false)
  const [availableTags, setAvailableTags] = useState<string[]>([])
  const [loadingTags, setLoadingTags] = useState(false)

  // 本地存储
  const [searchHistory, setSearchHistory] = useLocalStorage<string[]>('script-search-history', [])
  const [savedSearches, setSavedSearches] = useLocalStorage<SavedSearch[]>('saved-searches', [])
  const [recentTags, setRecentTags] = useLocalStorage<string[]>('recent-tags', [])

  // 表单
  const [filterForm] = Form.useForm()
  const [saveSearchForm] = Form.useForm()

  // 防抖搜索
  const debouncedKeyword = useDebounce(keyword, 300)

  // 排序选项
  const sortOptions = [
    { value: 'name', label: '名称', icon: <TagOutlined /> },
    { value: 'created_at', label: '创建时间', icon: <CalendarOutlined /> },
    { value: 'updated_at', label: '更新时间', icon: <CalendarOutlined /> },
    { value: 'last_executed_at', label: '最后执行时间', icon: <CalendarOutlined /> },
  ]

  // 加载可用标签
  const loadAvailableTags = useCallback(async () => {
    setLoadingTags(true)
    try {
      const response = await getAllTags()
      if (response.success) {
        setAvailableTags(response.data || [])
      }
    } catch (error) {
      console.error('加载标签失败:', error)
    } finally {
      setLoadingTags(false)
    }
  }, [])

  // 处理搜索
  const handleSearch = useCallback((value: string) => {
    setKeyword(value)
    
    // 添加到搜索历史
    if (value.trim() && !searchHistory.includes(value.trim())) {
      const newHistory = [value.trim(), ...searchHistory.slice(0, 9)] // 保留最近10条
      setSearchHistory(newHistory)
    }
    
    onSearch?.(value)
  }, [searchHistory, setSearchHistory, onSearch])

  // 处理标签变化
  const handleTagsChange = useCallback((tags: string[]) => {
    setSelectedTags(tags)
    
    // 更新最近使用的标签
    const newRecentTags = [...new Set([...tags, ...recentTags])].slice(0, 10)
    setRecentTags(newRecentTags)
    
    onTagsChange?.(tags)
  }, [recentTags, setRecentTags, onTagsChange])

  // 处理排序变化
  const handleSortChange = useCallback((newSortBy: string, newSortOrder?: 'asc' | 'desc') => {
    const finalSortOrder = newSortOrder || (newSortBy === sortBy && sortOrder === 'desc' ? 'asc' : 'desc')
    setSortBy(newSortBy)
    setSortOrder(finalSortOrder)
    onSortChange?.(newSortBy, finalSortOrder)
  }, [sortBy, sortOrder, onSortChange])

  // 处理高级过滤器变化
  const handleFilterChange = useCallback((newFilters: FilterOptions) => {
    setFilters(newFilters)
    onFilterChange?.(newFilters)
  }, [onFilterChange])

  // 清除所有过滤条件
  const handleClearAll = () => {
    setKeyword('')
    setSelectedTags([])
    setFilters({})
    filterForm.resetFields()
    
    onSearch?.('')
    onTagsChange?.([])
    onFilterChange?.({})
  }

  // 保存搜索条件
  const handleSaveSearch = (values: { name: string; isFavorite: boolean }) => {
    const newSavedSearch: SavedSearch = {
      id: Date.now().toString(),
      name: values.name,
      keyword,
      tags: selectedTags,
      filters,
      sortBy,
      sortOrder,
      createdAt: new Date().toISOString(),
      isFavorite: values.isFavorite,
    }
    
    setSavedSearches(prev => [newSavedSearch, ...prev])
    setSaveSearchModalVisible(false)
    saveSearchForm.resetFields()
    message.success('搜索条件已保存')
  }

  // 应用保存的搜索
  const handleApplySavedSearch = (savedSearch: SavedSearch) => {
    setKeyword(savedSearch.keyword)
    setSelectedTags(savedSearch.tags)
    setFilters(savedSearch.filters)
    setSortBy(savedSearch.sortBy)
    setSortOrder(savedSearch.sortOrder)
    
    filterForm.setFieldsValue(savedSearch.filters)
    
    onSearch?.(savedSearch.keyword)
    onTagsChange?.(savedSearch.tags)
    onFilterChange?.(savedSearch.filters)
    onSortChange?.(savedSearch.sortBy, savedSearch.sortOrder)
    
    setSearchHistoryVisible(false)
  }

  // 删除保存的搜索
  const handleDeleteSavedSearch = (id: string) => {
    setSavedSearches(prev => prev.filter(search => search.id !== id))
    message.success('已删除保存的搜索')
  }

  // 切换收藏状态
  const handleToggleFavorite = (id: string) => {
    setSavedSearches(prev => 
      prev.map(search => 
        search.id === id 
          ? { ...search, isFavorite: !search.isFavorite }
          : search
      )
    )
  }

  // 计算活跃过滤器数量
  const activeFiltersCount = useMemo(() => {
    let count = 0
    if (selectedTags.length > 0) count++
    if (filters.dateRange) count++
    if (filters.createdBy && filters.createdBy.length > 0) count++
    if (filters.hasDescription !== undefined) count++
    if (filters.hasContent !== undefined) count++
    if (filters.minVersions !== undefined || filters.maxVersions !== undefined) count++
    if (filters.lastExecutedRange) count++
    if (filters.contentLength?.min !== undefined || filters.contentLength?.max !== undefined) count++
    return count
  }, [selectedTags, filters])

  // 搜索历史菜单
  const searchHistoryMenu = {
    items: [
      ...searchHistory.map((item, index) => ({
        key: `history-${index}`,
        label: (
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text ellipsis style={{ maxWidth: 200 }}>{item}</Text>
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              onClick={(e) => {
                e.stopPropagation()
                setSearchHistory(prev => prev.filter((_, i) => i !== index))
              }}
            />
          </div>
        ),
        onClick: () => handleSearch(item),
      })),
      searchHistory.length > 0 && {
        type: 'divider' as const,
      },
      {
        key: 'clear-history',
        label: '清除搜索历史',
        icon: <ClearOutlined />,
        onClick: () => setSearchHistory([]),
      },
    ].filter(Boolean),
  }

  // 初始化
  useEffect(() => {
    loadAvailableTags()
  }, [loadAvailableTags])

  // 防抖搜索
  useEffect(() => {
    if (debouncedKeyword !== defaultKeyword) {
      onSearch?.(debouncedKeyword)
    }
  }, [debouncedKeyword, onSearch, defaultKeyword])

  return (
    <div>
      <Row gutter={[12, 12]} align="middle">
        {/* 搜索框 */}
        <Col flex="auto">
          <Search
            placeholder="搜索脚本名称或内容..."
            value={keyword}
            onChange={(e) => setKeyword(e.target.value)}
            onSearch={handleSearch}
            allowClear
            size="middle"
            suffix={
              searchHistory.length > 0 && (
                <Dropdown menu={searchHistoryMenu} trigger={['click']}>
                  <Button type="text" size="small" icon={<HistoryOutlined />} />
                </Dropdown>
              )
            }
          />
        </Col>

        {/* 标签选择 */}
        <Col flex="300px">
          <Select
            mode="multiple"
            placeholder="选择标签..."
            value={selectedTags}
            onChange={handleTagsChange}
            loading={loadingTags}
            allowClear
            maxTagCount="responsive"
            style={{ width: '100%' }}
            dropdownRender={(menu) => (
              <div>
                {menu}
                {recentTags.length > 0 && (
                  <>
                    <Divider style={{ margin: '8px 0' }} />
                    <div style={{ padding: '8px' }}>
                      <Text type="secondary" style={{ fontSize: 12 }}>最近使用:</Text>
                      <div style={{ marginTop: 4 }}>
                        {recentTags.slice(0, 5).map(tag => (
                          <Tag
                            key={tag}
                            style={{ cursor: 'pointer', marginBottom: 4 }}
                            onClick={() => {
                              if (!selectedTags.includes(tag)) {
                                handleTagsChange([...selectedTags, tag])
                              }
                            }}
                          >
                            {tag}
                          </Tag>
                        ))}
                      </div>
                    </div>
                  </>
                )}
              </div>
            )}
          >
            {availableTags.map(tag => (
              <Option key={tag} value={tag}>
                {tag}
              </Option>
            ))}
          </Select>
        </Col>

        {/* 排序选择 */}
        {showSortOptions && (
          <Col flex="none">
            <Space.Compact>
              <Select
                value={sortBy}
                onChange={(value) => handleSortChange(value)}
                style={{ width: 120 }}
              >
                {sortOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    <Space size={4}>
                      {option.icon}
                      {option.label}
                    </Space>
                  </Option>
                ))}
              </Select>
              <Button
                icon={sortOrder === 'asc' ? <SortAscendingOutlined /> : <SortDescendingOutlined />}
                onClick={() => handleSortChange(sortBy, sortOrder === 'asc' ? 'desc' : 'asc')}
                title={sortOrder === 'asc' ? '升序' : '降序'}
              />
            </Space.Compact>
          </Col>
        )}

        {/* 高级过滤器 */}
        {showAdvancedFilter && (
          <Col flex="none">
            <Badge count={activeFiltersCount} size="small">
              <Button
                icon={<FilterOutlined />}
                onClick={() => setFilterDrawerVisible(true)}
              >
                过滤器
              </Button>
            </Badge>
          </Col>
        )}

        {/* 操作按钮 */}
        <Col flex="none">
          <Space>
            {showSaveSearch && (
              <Tooltip title="保存搜索条件">
                <Button
                  icon={<SaveOutlined />}
                  onClick={() => setSaveSearchModalVisible(true)}
                  disabled={!keyword && selectedTags.length === 0 && activeFiltersCount === 0}
                />
              </Tooltip>
            )}
            
            <Tooltip title="搜索历史">
              <Button
                icon={<HistoryOutlined />}
                onClick={() => setSearchHistoryVisible(true)}
              />
            </Tooltip>
            
            <Tooltip title="清除所有条件">
              <Button
                icon={<ClearOutlined />}
                onClick={handleClearAll}
                disabled={!keyword && selectedTags.length === 0 && activeFiltersCount === 0}
              />
            </Tooltip>
          </Space>
        </Col>
      </Row>

      {/* 高级过滤器抽屉 */}
      <Drawer
        title="高级过滤器"
        placement="right"
        width={400}
        open={filterDrawerVisible}
        onClose={() => setFilterDrawerVisible(false)}
        extra={
          <Space>
            <Button onClick={() => filterForm.resetFields()}>重置</Button>
            <Button
              type="primary"
              onClick={() => {
                const values = filterForm.getFieldsValue()
                handleFilterChange(values)
                setFilterDrawerVisible(false)
              }}
            >
              应用
            </Button>
          </Space>
        }
      >
        <Form
          form={filterForm}
          layout="vertical"
          initialValues={filters}
        >
          <Form.Item name="dateRange" label="创建时间">
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item name="createdBy" label="创建者">
            <Select mode="multiple" placeholder="选择创建者..." allowClear>
              {/* 这里应该从API获取用户列表 */}
            </Select>
          </Form.Item>

          <Form.Item label="脚本属性">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Form.Item name="hasDescription" valuePropName="checked" noStyle>
                <Checkbox>包含描述</Checkbox>
              </Form.Item>
              <Form.Item name="hasContent" valuePropName="checked" noStyle>
                <Checkbox>包含内容</Checkbox>
              </Form.Item>
            </Space>
          </Form.Item>

          <Form.Item label="版本数量">
            <Row gutter={8}>
              <Col span={12}>
                <Form.Item name="minVersions" noStyle>
                  <Input placeholder="最少" type="number" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="maxVersions" noStyle>
                  <Input placeholder="最多" type="number" />
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>

          <Form.Item name="lastExecutedRange" label="最后执行时间">
            <RangePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item label="内容长度">
            <Row gutter={8}>
              <Col span={12}>
                <Form.Item name={['contentLength', 'min']} noStyle>
                  <Input placeholder="最少字符" type="number" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name={['contentLength', 'max']} noStyle>
                  <Input placeholder="最多字符" type="number" />
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 搜索历史抽屉 */}
      <Drawer
        title="搜索历史"
        placement="right"
        width={400}
        open={searchHistoryVisible}
        onClose={() => setSearchHistoryVisible(false)}
      >
        <div>
          {/* 保存的搜索 */}
          <div style={{ marginBottom: 24 }}>
            <Text strong>保存的搜索</Text>
            {savedSearches.length > 0 ? (
              <List
                size="small"
                dataSource={savedSearches}
                renderItem={(item) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        size="small"
                        icon={item.isFavorite ? <StarFilled /> : <StarOutlined />}
                        onClick={() => handleToggleFavorite(item.id)}
                      />,
                      <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={() => handleDeleteSavedSearch(item.id)}
                      />,
                    ]}
                  >
                    <List.Item.Meta
                      title={
                        <Button
                          type="link"
                          style={{ padding: 0, height: 'auto' }}
                          onClick={() => handleApplySavedSearch(item)}
                        >
                          {item.name}
                        </Button>
                      }
                      description={
                        <div>
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            {item.keyword && `关键词: ${item.keyword}`}
                            {item.tags.length > 0 && ` | 标签: ${item.tags.join(', ')}`}
                          </Text>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无保存的搜索" style={{ margin: '16px 0' }} />
            )}
          </div>

          {/* 搜索历史 */}
          <div>
            <Text strong>搜索历史</Text>
            {searchHistory.length > 0 ? (
              <List
                size="small"
                dataSource={searchHistory}
                renderItem={(item, index) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={() => setSearchHistory(prev => prev.filter((_, i) => i !== index))}
                      />,
                    ]}
                  >
                    <Button
                      type="link"
                      style={{ padding: 0, height: 'auto', textAlign: 'left' }}
                      onClick={() => handleSearch(item)}
                    >
                      {item}
                    </Button>
                  </List.Item>
                )}
              />
            ) : (
              <Empty description="暂无搜索历史" style={{ margin: '16px 0' }} />
            )}
          </div>
        </div>
      </Drawer>

      {/* 保存搜索模态框 */}
      <Modal
        title="保存搜索条件"
        open={saveSearchModalVisible}
        onCancel={() => setSaveSearchModalVisible(false)}
        onOk={() => saveSearchForm.submit()}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={saveSearchForm}
          layout="vertical"
          onFinish={handleSaveSearch}
        >
          <Form.Item
            name="name"
            label="搜索名称"
            rules={[{ required: true, message: '请输入搜索名称' }]}
          >
            <Input placeholder="为这个搜索条件起个名字..." />
          </Form.Item>
          
          <Form.Item name="isFavorite" valuePropName="checked">
            <Checkbox>添加到收藏</Checkbox>
          </Form.Item>

          <div style={{ padding: 12, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
            <Text type="secondary" style={{ fontSize: 12 }}>预览:</Text>
            <div style={{ marginTop: 8 }}>
              {keyword && <div>关键词: {keyword}</div>}
              {selectedTags.length > 0 && <div>标签: {selectedTags.join(', ')}</div>}
              {activeFiltersCount > 0 && <div>高级过滤器: {activeFiltersCount} 个条件</div>}
              <div>排序: {sortOptions.find(opt => opt.value === sortBy)?.label} ({sortOrder === 'asc' ? '升序' : '降序'})</div>
            </div>
          </div>
        </Form>
      </Modal>
    </div>
  )
}

export default SearchAndFilter